package com.ruoyi.pos.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.pos.domain.device.PosDevice;
import com.ruoyi.pos.domain.dto.device.request.DeviceAutoRegisterRequest;
import com.ruoyi.pos.domain.dto.device.request.DeviceDebugCommandRequest;
import com.ruoyi.pos.domain.dto.device.response.DeviceAutoRegisterResponse;
import com.ruoyi.pos.domain.dto.device.response.DeviceDebugLogResponse;
import com.ruoyi.pos.service.device.IPosDeviceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * POS设备Controller
 * 
 * @author ruoyi
 * @date 2025-01-30
 */
@Api(tags = "POS设备管理")
@RestController
@RequestMapping("/pos/device")
public class PosDeviceController extends BaseController {

    @Autowired
    private IPosDeviceService posDeviceService;

    /**
     * 设备自动注册（安卓端调用）
     */
    @ApiOperation("设备自动注册")
    @PostMapping("/autoRegister")
    public AjaxResult autoRegister(@RequestBody DeviceAutoRegisterRequest request) {
        try {
            DeviceAutoRegisterResponse response = posDeviceService.autoRegisterDevice(request);
            return success(response);
        } catch (Exception e) {
            return error("设备注册失败：" + e.getMessage());
        }
    }

    /**
     * 根据设备编码查询设备（安卓端调用）
     */
    @ApiOperation("根据设备编码查询设备")
    @GetMapping("/code/{deviceCode}")
    public AjaxResult getDeviceByCode(@PathVariable String deviceCode) {
        try {
            PosDevice device = posDeviceService.selectPosDeviceByCode(deviceCode);
            if (device != null) {
                return success(device);
            } else {
                return error("设备不存在");
            }
        } catch (Exception e) {
            return error("查询设备失败：" + e.getMessage());
        }
    }

    /**
     * 查询设备列表
     */
    @ApiOperation("查询设备列表")
    @PreAuthorize("@ss.hasPermi('pos:device:list')")
    @GetMapping("/list")
    public TableDataInfo list(PosDevice posDevice) {
        startPage();
        List<PosDevice> list = posDeviceService.selectPosDeviceList(posDevice);
        return getDataTable(list);
    }

    /**
     * 导出设备列表
     */
    @ApiOperation("导出设备列表")
    @PreAuthorize("@ss.hasPermi('pos:device:export')")
    @Log(title = "POS设备", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PosDevice posDevice) {
        List<PosDevice> list = posDeviceService.selectPosDeviceList(posDevice);
        ExcelUtil<PosDevice> util = new ExcelUtil<PosDevice>(PosDevice.class);
        util.exportExcel(response, list, "POS设备数据");
    }

    /**
     * 获取设备详细信息
     */
    @ApiOperation("获取设备详细信息")
    @PreAuthorize("@ss.hasPermi('pos:device:query')")
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId) {
        return success(posDeviceService.selectPosDeviceByDeviceId(deviceId));
    }

    /**
     * 新增设备
     */
    @ApiOperation("新增设备")
    @PreAuthorize("@ss.hasPermi('pos:device:add')")
    @Log(title = "POS设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PosDevice posDevice) {
        return toAjax(posDeviceService.insertPosDevice(posDevice));
    }

    /**
     * 修改设备
     */
    @ApiOperation("修改设备")
    @PreAuthorize("@ss.hasPermi('pos:device:edit')")
    @Log(title = "POS设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PosDevice posDevice) {
        return toAjax(posDeviceService.updatePosDevice(posDevice));
    }

    /**
     * 删除设备
     */
    @ApiOperation("删除设备")
    @PreAuthorize("@ss.hasPermi('pos:device:remove')")
    @Log(title = "POS设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deviceIds}")
    public AjaxResult remove(@PathVariable Long[] deviceIds) {
        return toAjax(posDeviceService.deletePosDeviceByDeviceIds(deviceIds));
    }

    /**
     * 更新设备状态
     */
    @ApiOperation("更新设备状态")
    @PreAuthorize("@ss.hasPermi('pos:device:edit')")
    @Log(title = "设备状态更新", businessType = BusinessType.UPDATE)
    @PutMapping("/status/{deviceId}/{status}")
    public AjaxResult updateStatus(@PathVariable Long deviceId, @PathVariable String status) {
        return toAjax(posDeviceService.updatePosDeviceStatus(deviceId, status));
    }

    /**
     * 获取设备心跳信息
     */
    @ApiOperation("获取设备心跳信息")
    @PreAuthorize("@ss.hasPermi('pos:device:query')")
    @GetMapping("/heartbeat/{deviceId}")
    public AjaxResult getHeartbeat(@PathVariable Long deviceId) {
        return success(posDeviceService.getDeviceHeartbeat(deviceId));
    }

    /**
     * 设备配置更新
     */
    @ApiOperation("设备配置更新")
    @PreAuthorize("@ss.hasPermi('pos:device:edit')")
    @Log(title = "设备配置更新", businessType = BusinessType.UPDATE)
    @PutMapping("/config/{deviceId}")
    public AjaxResult updateConfig(@PathVariable Long deviceId, @RequestBody Object configData) {
        return toAjax(posDeviceService.updateDeviceConfig(deviceId, configData));
    }

    /**
     * 发送调试指令到设备
     */
    @ApiOperation("发送调试指令到设备")
    @PreAuthorize("@ss.hasPermi('pos:device:edit')")
    @Log(title = "设备调试指令", businessType = BusinessType.UPDATE)
    @PostMapping("/debug/{deviceId}")
    public AjaxResult sendDebugCommand(@PathVariable Long deviceId, @RequestBody DeviceDebugCommandRequest request) {
        try {
            request.setDeviceId(deviceId);
            boolean result = posDeviceService.sendDebugCommand(request);
            return toAjax(result ? 1 : 0);
        } catch (Exception e) {
            return error("发送调试指令失败：" + e.getMessage());
        }
    }

    /**
     * 获取设备调试日志
     */
    @ApiOperation("获取设备调试日志")
    @PreAuthorize("@ss.hasPermi('pos:device:query')")
    @GetMapping("/debug/logs/{deviceId}")
    public TableDataInfo getDeviceDebugLogs(@PathVariable Long deviceId, DeviceDebugLogResponse query) {
        startPage();
        List<DeviceDebugLogResponse> list = posDeviceService.getDeviceDebugLogs(deviceId, query);
        return getDataTable(list);
    }

    /**
     * 清除设备调试日志
     */
    @ApiOperation("清除设备调试日志")
    @PreAuthorize("@ss.hasPermi('pos:device:edit')")
    @Log(title = "清除设备调试日志", businessType = BusinessType.DELETE)
    @PostMapping("/debug/clear/{deviceId}")
    public AjaxResult clearDeviceDebugLogs(@PathVariable Long deviceId) {
        return toAjax(posDeviceService.clearDeviceDebugLogs(deviceId));
    }
}
